package com.qf.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取sqlSession对象
     *
     * @return
     */
    public static SqlSession openSession() {
        SqlSession sqlSession = local.get();
        if (sqlSession == null) {
            //默认sqlSession不自动提交
            sqlSession = factory.openSession();
            //设置sqlSession自动提交
            //sqlSession = factory.openSession(true);
            local.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 提交
     */
    public static void commit() {
        SqlSession sqlSession = openSession();
        sqlSession.commit();
        closeSession();
    }

    /**
     * 回滚
     */
    public static void rollback() {
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSession();
    }

    /**
     * 关闭sqlSession
     */
    public static void closeSession() {
        SqlSession sqlSession = openSession();
        sqlSession.close();
        local.remove();
    }

    /**
     * 获取Mapper对象
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T extends Object> T getMapper(Class<T> clazz) {
        T dao = openSession().getMapper(clazz);
        return dao;
    }

}